<template>
        <!-- 侧边栏 -->
        <div :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
            class="flex flex-col w-64 backdrop-blur-sm bg-white/80 rounded-r-3xl py-4
                transition-transform duration-300 ease-in-out z-10 overflow-y-auto">
            <!-- AI 信息以及收起侧边栏按钮 -->
            <div class="flex h-fit items-center font-bold justify-around">

                <!-- AI 头像 -->
                <img src="http://t4hiq2jzc.hn-bkt.clouddn.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250208182804.jpg"
                    class="w-[50px] h-[50px] rounded-full items-center"
                    @click="jumpToIndexPage">

                黑夜 AI 机器人

                <a-tooltip 
                    placement="bottom"
                    :open="tooltipVisible && sidebarOpen"
                    >
                    <template #title>
                        <span>收缩边栏</span>
                    </template>

                    <button
                        @click="toggleSidebar"
                        @mouseenter="handleMouseEnter"
                        @mouseleave="handleMouseLeave"
                        >

                        <!-- 图标 -->
                        <Icon icon="material-symbols:left-panel-close-rounded" 
                            class="w-6 h-6 text-[#333333]"/>
                    </button>
                </a-tooltip>
            </div>

            <!-- 新对话、智能体、 ai 工具 -->
            <div class="flex flex-col my-5">
                <template v-for="(icon, index) in icons" :key="index">
                    <router-link :to="{ name: icon.name }"
                            @click="selectedFunction(index)"
                            class="active:scale-95 mx-2 px-2 py-1.5 cursor-pointer font-medium rounded-xl transition-all duration-300 ease-in-out"
                            :class="selectedFunctionIndex === index ? 'bg-[#E6F0FF] text-[#3B5BFF]' : 'hover:bg-[#FFEBEE]'">
                        <div class="flex items-center gap-3">
                            <SvgIcon :name="icon.icon" class="w-[1.2rem] h-[1.2rem] inline"></SvgIcon>
                            {{ icon.text }}
                        </div>
                    </router-link>
                </template>
            </div>

            <!-- 聊天记录标题 -->
            <div class="text-xs px-5 py-1 mb-1 text-gray-500">聊天记录</div>

            <!-- 聊天记录 -->
            <div 
                :class="isHistoryChatLoading ? 'opacity-0' : 'opacity-100'"
                class="px-2 overflow-hidden flex-1 transition-opacity duration-300 ease-in-out custom-scrollbar hover:overflow-y-auto"
                ref="historyChatContainerRef">
                <div class="space-y-1">
                    <!-- 历史对话 -->
                    <div v-for="(historyChat, index) in historyChats" 
                        :key="index">

                        <!-- 对话信息 -->
                        <div :class="['relative px-3 py-1 rounded-3xl cursor-pointer transition-all flex items-center duration-300 ease-in-out active:scale-95',
                            selectedChatId === historyChat.uuid ? 'bg-[#E6F0FF] text-[#3B5BFF]' : 'hover:bg-[#FFEBEE]']"
                            @click="jumpToChatPage(historyChat.uuid, historyChat.roleId)"
                            @mouseenter="showButton = historyChat.uuid" @mouseleave="showButton = null">

                            <!-- 头像 TODO: 要获取真正的角色头像 -->
                            <img :src="historyChat.roleAvatar ? historyChat.roleAvatar : 'http://t4hiq2jzc.hn-bkt.clouddn.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241031141912.jpg'"
                                class="w-8 h-8 rounded-full items-center">
                            
                            <div v-if="historyChat.id !== formState.id" class="min-w-0">
                                <!-- 对话简要 -->
                                <p class="ml-3 text-[14px] overflow-hidden whitespace-nowrap text-ellipsis">{{ historyChat.summary }}</p>

                                <!-- 下拉菜单 -->
                                <a-dropdown>
                                    <template #overlay>
                                        <a-menu @click="handleMenuClick(historyChat.uuid, historyChat.id, historyChat.roleId, historyChat.summary, $event)">
                                            <a-menu-item key="rename">
                                                <Icon icon="material-symbols:stylus-note" class="w-4 h-4 text-[#333333] inline-block align-middle mr-2" />
                                                重命名
                                            </a-menu-item>
                                            <a-menu-item key="delete" danger>
                                                <Icon icon="material-symbols:delete" class="w-4 h-4 text-[#333333] inline-block align-middle mr-2" />
                                                删除
                                            </a-menu-item>
                                        </a-menu>
                                    </template>
                                    <!-- 右边菜单按钮 -->
                                    <button
                                        class="z-10 rounded-3xl outline-none justify-center items-center
                                            w-6 h-6 flex absolute right-2 top-1/2 transform -translate-y-1/2 transition-all duration-300 hover:bg-gray-50"
                                        :style="{ opacity: showButton === historyChat.uuid ? 1 : 0 }">
                                        <Icon icon="material-symbols:more-horiz" class="w-4 h-4 text-gray-500" />
                                    </button>
                                </a-dropdown>
                            </div>

                            <!-- 重命名对话简要 -->
                            <input v-else class="ml-1 px-2 rounded-3xl transition-colors flex items-center text-[#3B5BFF] text-[14px] whitespace-nowrap overflow-hidden
                                    outline-none focus:outline-none border focus:border-[#3B5BFF]" 
                                    :value="formState.summary"
                                    type="text"
                                    :ref="setRenameInputRef"
                                    @blur="handleRenameInputBlur"
                                    @keyup.enter="handleRenameInputOK"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 展开侧边栏按钮 -->
        <div :class="!sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
            class="bg-white/90 rounded-r-2xl my-2 fixed x-0 border-0
                h-fit p-2 flex items-center justify-center gap-2
                transition-all duration-300 ease-in-out z-10 overflow-y-auto"
            >

            <!-- AI 头像-->
            <img src="http://t4hiq2jzc.hn-bkt.clouddn.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250208182804.jpg"
                class="w-10 h-10 rounded-full items-center">

            <a-tooltip 
                placement="bottom"
                :open="tooltipVisible && !sidebarOpen"
                >
                <!-- Tooltip 提示文字 -->
                <template #title>
                    <span>打开边栏</span>
                </template>
                
                <button
                    @click="toggleSidebar"
                    @mouseenter="handleMouseEnter"
                    @mouseleave="handleMouseLeave"
                    >

                    <!-- 展开图标 -->
                    <Icon icon="material-symbols:left-panel-open" 
                        class="w-6 h-6 text-[#333333] "/>
                </button>
            </a-tooltip>
        </div>

        <!-- 删除对话确认框 -->
        <div class="fixed inset-0 z-50 transition-all duration-300 ease-in-out
                flex items-center justify-center"
            :class="deleteChatModelOpen ? 'opacity-100 visible' : 'opacity-0 invisible'">

            <!-- 黑色遮罩（单独动画） -->
            <div class="absolute inset-0 transition-all duration-300"
                :class="deleteChatModelOpen ? 'bg-black/50' : 'bg-black/0'"
                @click="deleteChatModelOpen = false">
            </div>

            <!-- 对话框 -->
            <dvi class="relative flex flex-col bg-white w-[400px] rounded-3xl transition-all duration-300 ease-in-out
                p-5 gap-5"
                :class="deleteChatModelOpen ? 'opacity-100 visible scale-100' : 'opacity-0 invisible scale-90'">
                <div class="text-[#333333] font-semibold">
                    永久删除对话
                </div>

                <div class="text-[#3F3F3F] text-sm">
                    删除后，该对话将不可恢复。确认删除吗？
                </div>

                <div class="flex justify-end gap-5 text-sm">
                    <button class="border border-xs border-gray-200 rounded-xl px-3 py-1 hover:bg-gray-100 transition-colors"
                        @click="deleteChatModelOpen = false">
                        取消
                    </button>
                    <button class="border border-xs border-red-400 text-red-400 rounded-xl px-3 py-1 hover:bg-red-50 transition-colors"
                        @click="handleDeleteChatModelOk()">
                        删除
                    </button>
                </div>
            </dvi>
        </div>
</template>

<script setup>
import { Icon } from "@iconify/vue";
import { ref, onMounted, onBeforeUnmount, reactive, nextTick, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// 导入获取历史对话列表的API
import { deleteChat, findHistoryChatPageList, renameChat } from '@/api/chat'
import SvgIcon from "../common/SvgIcon.vue";
// 导入Pinia store
import { useHistoryChatsStore } from '@/stores/historyChatsStore'
import { useRoleChatStore } from "@/stores/roleChatStore";
import { message } from "ant-design-vue";

// 获取 chat store
const historyChatsStore = useHistoryChatsStore()
// 获取 roleChat store
const roleChatStore = useRoleChatStore()

const router = useRouter()

const route = useRoute()

const icons = [
    { icon: 'edit', text: '新聊天', name: 'AI' },
    { icon: 'deployed-code', text: '角色', name: 'Role' },
    { icon: 'toolbox', text: '工具箱', name: 'Toolbox' },
]

// 定义 props, 对外部暴露配置项
const props = defineProps({
  // 左边栏是否展开
  sidebarOpen: { 
    type: Boolean, 
    required: true 
  },
})

// 定义 emits
const emit = defineEmits(['toggle-sidebar'])

// 切换侧边栏显示/隐藏
const toggleSidebar = () => {
  // 先立即隐藏 Tooltip
  tooltipVisible.value = false
  // 然后切换侧边栏
  emit('toggle-sidebar')
}

// a-tooltip 的显隐状态控制
const tooltipVisible = ref(false)

// 鼠标悬停事件
const handleMouseEnter = () => {
  tooltipVisible.value = true
}

// 鼠标离开事件
const handleMouseLeave = () => {
  tooltipVisible.value = false
}

// 历史对话
const historyChats = computed(() => historyChatsStore.historyChats)

// 当前显示右侧栏按钮的聊天 ID
const showButton = ref(null)

// 当前选中的聊天 ID
const selectedChatId = ref(null)

// 当前选中的功能索引
const selectedFunctionIndex = ref(0)

// 左边栏滚动区域引用
const historyChatContainerRef = ref(null)

onMounted(() => {
  // 查询历史对话
  fetchHistoryChats()

  // 检查当前路由是否有 chatId 参数
  const currentChatId = route.params.chatId
  if (currentChatId) {
    // 设置当前选中的对话 ID
    selectedChatId.value = currentChatId
  }

  // 添加滚动监听事件
  if (historyChatContainerRef.value) {
    historyChatContainerRef.value.addEventListener('scroll', handleScroll);
  }
})

onBeforeUnmount(() => {
  // 移除滚动事件监听
  if (historyChatContainerRef.value) {
    historyChatContainerRef.value.removeEventListener('scroll', handleScroll);
  }
})

// 分页相关状态
// 当前页码（默认第一页）
const current = ref(1)
// 每页展示数据量
const size = ref(20)
// 是否还有下一页数据（默认有）
const hasMore = ref(true)
// 是否正在加载中 (解决并发请求后续页数据问题)
const isLoadingMore = ref(false)
// 历史对话列表首次加载动画
const isHistoryChatLoading = ref(true)

const handleScroll = () => {
    if (historyChatContainerRef.value && hasMore.value && !isLoadingMore.value) {
        // 获取滚动参数
        const { scrollTop, scrollHeight, clientHeight } = historyChatContainerRef.value;
        // 距离底部距离
        const scrollPosition = scrollHeight - scrollTop - clientHeight;

        // 打印滚动过程中的详细日志
        console.log('=== 滚动事件日志 ===')
        console.log('scrollPosition:', scrollPosition)

        // 当滚动到距离底部 20 px 以内时，加载更多
        if (scrollPosition <= 20) {
            loadMoreHistoryChats()
        }
    }
}

// 加载更多历史对话
const loadMoreHistoryChats = async () => {
    console.log('=== 开始加载更多历史消息 ===')
    console.log('当前页码:', current.value)

    // 双重检查：
    // 1. 如果当前页面已经是最后一页，则不再发送请求
    // 2. 如果已经有请求在进行中，则不再发送请求
    if (!hasMore.value) {
        console.log('=== 没有更多历史对话，不再请求 ===')
        return
    }
    
    if (isLoadingMore.value) {
        console.log('=== 已有加载请求正在进行中，不再发送新请求 ===')
        return
    }

    // 设置加载状态为 true，防止并发请求
    isLoadingMore.value = true

    // 计算下一页页码（向下滑动加载更早的历史对话，页码应该增加）
    const nextPageNo = current.value + 1
    console.log('=== 计算下一页页码 ===', nextPageNo)

    // 保存当前页码用于错误恢复
    const currentTemp = current.value
    // 当前需要请求的页码
    current.value = nextPageNo

    try {
        await fetchHistoryChats();
    } catch (error) {
        // 如果请求失败，则恢复当前页码
        current.value = currentTemp
    }
}

// 获取历史对话列表
const fetchHistoryChats = async () => {
    findHistoryChatPageList(current.value, size.value).then(res =>{
        // 无论成功失败，请求完成后都需要重置加载状态
        isLoadingMore.value = false

        if (res.data.success) {
            const data = res.data.data

            // 判断是否还有下一页(总页数 > 当前页)
            hasMore.value = res.data.pages > current.value

            if (data && data.length > 0) {
                // 将新数据添加到历史对话列表末尾
                historyChatsStore.addMoreChatHistoryMessage(data)

                // 初次加载，触发动画
                if (current.value === 1) {
                    isHistoryChatLoading.value = false
                    console.log('=== 触发历史对话列表加载动画 ===')
                }
            }
        }
    }).catch((error) => {
        // 错误处理，重置加载状态
        console.error('加载历史对话失败:', error)
        isLoadingMore.value = false
    })
}

// 跳转历史对话页
const jumpToChatPage = (chatId, roleId) => {

    // 将选择的功能索引置空
    selectedFunctionIndex.value = null

    // 更新被选中的对话 ID
    selectedChatId.value = chatId

    // roleId 为 1 时，说明该角色是系统的 AI 角色，跳转到普通的聊天界面就好了
    if (roleId === 1) {
        router.push({ 
            name: 'Chat', 
            params: { chatId },
            query: {
                // 传递角色 ID 
                roleId
            }
        })
    } else {
        router.push({ name: 'RoleChat', params: { chatId }, query: { roleId } })
    }
}

// 删除对话确认框是否展示
const deleteChatModelOpen = ref(false)
// 被删除的对话 UUID
const deleteChatUUID = ref(null)
// 被删除的角色 ID
const deleteRoleId = ref(null)
// 重命名输入框
const renameInputRef = ref(null)

// 设置 ref 的函数，因为在 v-for 循环中无法直接获取到 ref，所以需要定义一个函数来设置 ref
const setRenameInputRef = (el) => {
  renameInputRef.value = el
}

// 处理菜单点击
const handleMenuClick = async (uuid, id, roleId, summary, e)  => {
     // 删除对话
    if (e.key === 'delete') {
        console.log('用户点击了删除对话：', uuid)
        // 展示确认框
        deleteChatModelOpen.value = true
        // 保存当前被删除的对话 UUID
        deleteChatUUID.value = uuid
        // 保存当前被删除的角色 ID
        deleteRoleId.value = Number(roleId)
    }
    // 重命名对话
    else if (e.key === 'rename') {
        console.log('用户点击了重命名对话：', uuid)

        // 保存当前被重命名的对话 ID
        formState.id = id
        // 保存摘要
        formState.summary = summary

        // 等待 DOM 更新
        await nextTick()    

        // 输入框获取焦点
        if (renameInputRef.value) {
            renameInputRef.value.focus()
        }

        console.log('表单数据：', formState)
    }
}

// 删除对话确认框确认事件
const handleDeleteChatModelOk = () => {
    deleteChat(deleteChatUUID.value).then((res) => {
        if (res.data.success) {
            message.success('删除成功')

            // 从 historyChats 数组中删除对应的对话
            historyChatsStore.deleteChatHistoryMessage(deleteChatUUID.value)

            // 如果删除的不是系统 AI 角色的对话，需要更新 roleChatStore 中的模型语言
            if (deleteRoleId.value !== 1) {
                roleChatStore.deleteSelectedRoleModel(deleteRoleId.value)
            }

            // 跳转首页
            router.push({ name: 'NewChat' })
        } else {
            // 提示错误信息
            message.error(res.data.message)
        }
    }).finally(() => {
        // 隐藏确认框
        deleteChatModelOpen.value = false
    })
}

// 表单对象
const formState = reactive({
    // 被重命名对话 ID
    id: null,
    // 被重命名对话摘要
    summary: ''
})

// 重命名对话输入框失去焦点事件
const handleRenameInputBlur = (event) => {
    console.log('输入框失去焦点：', event)

    // 触发确认事件
    handleRenameInputOK()
}

// 重命名对话确认框确认事件
const handleRenameInputOK = () => {
    // 获取输入框的值
    const newSummary = renameInputRef.value?.value

    // 判断输入框的值是否为空 或者是否与原始摘要相同
    if (!newSummary.trim() || newSummary.trim() === formState.summary) {
        
        // 重置表单数据
        formState.id = null
        formState.summary = ''

        return
    }

    renameChat(formState.id, newSummary).then((res) => {
        if (!res.data.success) {
            // 接口返回失败, 提示错误信息
            message.error(res.data.message)
            return
        }

        // 更新 historyChats 数组总对应 id 的对话摘要
        const chatIndex = historyChats.value.findIndex(item => item.id === formState.id);
        if (chatIndex !== -1) {
            historyChats.value[chatIndex].summary = newSummary
        }

    }).catch((error) => {
        // 错误处理
        console.log('error', error);

    }).finally(() => {
        // 无论如何，都重置表单数据
        formState.id = null
        formState.summary = ''
    })
}

// 跳转到首页
const jumpToIndexPage = () => {
    // 更新被选中的功能索引
    selectedFunction(0)

    router.push('/ai')
}

// 更新当前选中的功能索引
const selectedFunction = (index) => {
    // 更新被选中的函数索引
    selectedFunctionIndex.value = index

    // 将选中的聊天 ID 置空
    selectedChatId.value = null
}

watch(() => route.params?.chatId, (newValue) => {
    // 如果聊天 ID 发生改变，且存在，那么将选中的聊天高亮
    if (newValue) {
        // 将选择的功能索引置空
        selectedFunctionIndex.value = null

        // 更新被选中的对话 ID
        selectedChatId.value = newValue
    }
})
</script>

<style scoped>
</style>